<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2020/5/12} {10:15} 
 */

namespace libraries;


use app\logsystem\model\OpenApiRequestLog;
use think\Db;
use think\Exception;
use think\facade\Cache;

class HttpCacheUtility
{
    const NoCacheTime = 0;
    const LowCacheTime = 60 * 1;
    const NormalCacheTime = 60 * 10;
    const HighCacheTime = 60 * 60;
    const LongCacheTime = 60 * 60 * 24;

    /**
     * desc：开放平台接口请求
     * author：wh
     * @param string $url
     * @param array $params
     * @param int $cacheDuration
     * @return array|mixed
     */
    static function httpPostRequest(string $url, array $params, $cacheDuration = self::NoCacheTime){

        $key = md5($url.implode('', $params));
        if ($cacheDuration == 0) {
            if(cache($key)){
                cache($key, null);
            }
        }
        $start_time = Tools::getMillisecond();

        $is_cache = false;
        $req_data = [];
        $result = [];
        if (!(cache($key))) {
            $req_data = Tools::curl_post($url, json_encode($params));
            if($req_data['code'] == 200){
                $result = json_decode($req_data['data'], true);

            }

            if ($cacheDuration != 0) {
                cache($key, $result, $cacheDuration);
            }
        } else {
            $is_cache = true;
            $result = cache($key);
        }

        if(false == $is_cache){
            $end_time = Tools::getMillisecond();
            OpenApiRequestLog::setLog('开放平台接口请求'.encodeJson($params), $req_data, $end_time - $start_time);
        }
        return $result;
    }

}